package io.seata.samples.integration.call.service;

import com.alibaba.dubbo.config.annotation.Reference;

import com.esotericsoftware.minlog.Log;
import io.seata.core.context.RootContext;
import io.seata.integration.http.DefaultHttpExecutor;
import io.seata.samples.integration.common.dto.BusinessDTO;
import io.seata.samples.integration.common.dto.CommodityDTO;
import io.seata.samples.integration.common.dto.OrderDTO;
import io.seata.samples.integration.common.dubbo.OrderDubboService;
import io.seata.samples.integration.common.enums.RspStatusEnum;
import io.seata.samples.integration.common.exception.DefaultException;
import io.seata.samples.integration.common.response.ObjectResponse;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.math.BigDecimal;

/**
 * @Author: wwg
 * @Description  Dubbo业务发起方逻辑
 */
@Service
public class BusinessServiceImpl implements BusinessService{


    @Reference(version = "1.0.0",check = false)
    private OrderDubboService orderDubboService;

    /**
     * 处理业务逻辑
     * @Param:
     * @Return:
     */
    @Override
    @GlobalTransactional(timeoutMills = 300000, name = "gts-seata-handleBusiness")
    public ObjectResponse handleBusiness(BusinessDTO businessDTO) {
        System.out.println("开始全局事务，XID = " + RootContext.getXID());
        ObjectResponse<Object> objectResponse = new ObjectResponse<>();

        //调用订单服务——创建订单
        OrderDTO orderDTO = new OrderDTO();
        orderDTO.setUserId(businessDTO.getUserId());
        orderDTO.setCommodityCode(businessDTO.getCommodityCode());
        orderDTO.setOrderCount(businessDTO.getCount());
        orderDTO.setOrderAmount(businessDTO.getAmount());
        ObjectResponse<OrderDTO> response = orderDubboService.createOrder(orderDTO);

        //调用减库存服务——减库存、扣除账户余额
        CommodityDTO commodityDTO = new CommodityDTO();
        commodityDTO.setUserId(businessDTO.getUserId());
        commodityDTO.setCommodityCode(businessDTO.getCommodityCode());
        commodityDTO.setName(businessDTO.getName());
        commodityDTO.setCount(businessDTO.getCount());
        commodityDTO.setAmount(businessDTO.getAmount());

        try {
            DefaultHttpExecutor.getInstance().executePost("http://localhost:8201", "/storage/dec_storage", commodityDTO, ObjectResponse.class);
        } catch (IOException e) {
            Log.error(e.getMessage(),e);
        }

        if(businessDTO.getRollBackFlag()){
            int i = 1/0;
        }


        if (response.getStatus() != 200) {
            throw new DefaultException(RspStatusEnum.FAIL);
        }

        objectResponse.setStatus(RspStatusEnum.SUCCESS.getCode());
        objectResponse.setMessage(RspStatusEnum.SUCCESS.getMessage());
        objectResponse.setData(response.getData());
        return objectResponse;
    }
}
